from flask import Blueprint, request, jsonify
from app.models.database import get_db_connection
from app.utils.validators import (
    is_valid_email, is_valid_username,is_valid_password, generate_token, get_token_expires,hash_password,verify_password
)
from app.utils.response import APIResponse
from app.utils.status_code import StatusCode
from datetime import datetime
import pymysql

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/')
def index():
    """根路由，提供API基本信息"""
    return jsonify({
        'msg': '电池监控系统API11111111111111111',
        'version': '1.0',
        'endpoints': {
            'login': 'POST /login',
            'register': 'POST /register'
        }
    })

@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册接口"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify({
                'code': 400,
                'message': '请求体必须是JSON格式',
                'data': {}
            }), 400

        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        confirm_password = data.get('confirmPassword')
        role = data.get('role')

        # 验证必要参数
        if not all([username, email, password, role is not None]):
            return APIResponse.error('缺少必要参数: username, email, password, role', StatusCode.BAD_REQUEST)

        # 验证邮箱格式
        if not is_valid_email(email):
            return APIResponse.error('邮箱格式不正确', StatusCode.BAD_REQUEST)

        # 验证用户名格式
        if not is_valid_username(username):
            return APIResponse.error('用户名格式不正确（2-20位字母/数字/下划线）', StatusCode.BAD_REQUEST)

        # 验证密码格式
        if not is_valid_password(password):
            return APIResponse.error('密码格式不正确（6-20位字母+数字）', StatusCode.BAD_REQUEST)

        # 验证两次密码是否一致
        if password != confirm_password:
            return APIResponse.error('两次输入的密码不一致', StatusCode.BAD_REQUEST)

        # 哈希密码
        hashed_password = hash_password(password)

        # 连接数据库
        connection = get_db_connection()

        try:
            with connection.cursor() as cursor:
                # 检查邮箱是否已存在
                cursor.execute("SELECT user_id FROM user WHERE email = %s", (email,))
                if cursor.fetchone():
                    return APIResponse.error('该邮箱已被注册', StatusCode.BAD_REQUEST)

                # 检查用户名是否已存在
                cursor.execute("SELECT user_id FROM user WHERE username = %s", (username,))
                if cursor.fetchone():
                    return APIResponse.error('该用户名已被使用', StatusCode.BAD_REQUEST)

                # 插入新用户，直接设置为已通过状态
                current_time = datetime.now()
                sql = """
                INSERT INTO user (username, email, password, role, register_time)
                VALUES (%s, %s, %s, %s, %s)
                """
                cursor.execute(sql, (
                    username,
                    email,
                    hashed_password,
                    role,
                    current_time
                ))

                # 获取新插入的用户ID
                user_id = cursor.lastrowid

                # 提交事务
                connection.commit()

                return APIResponse.success(
                    data={
                        'userId': user_id,
                        'role': role
                    },
                    message='注册成功'
                )

        except pymysql.err.IntegrityError as e:
            # 处理可能的唯一性约束错误
            return APIResponse.error('注册失败，用户名或邮箱可能已被使用', StatusCode.BAD_REQUEST)

        finally:
            connection.close()

    except Exception as e:
        return APIResponse.server_error(f'服务器错误: {str(e)}')

@auth_bp.route('/login', methods=['POST', 'GET'])
def login():
    """登录接口，支持POST请求，GET请求返回方法信息"""

    if request.method == 'GET':
        return APIResponse.success(
            data={
                'msg': '请使用POST方法登录',
                'example_request': {
                    'email': 'user@example.com',
                    'password': 'yourpassword',
                    'role': 0
                }
            }
        )

    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return APIResponse.error('请求体必须是JSON格式', StatusCode.BAD_REQUEST)

        email = data.get('email')
        password = data.get('password')
        role = data.get('role')
        remember_me = data.get('rememberMe', False)

        # 验证必要参数
        if not all([email, password, role is not None]):
            return APIResponse.error('缺少必要参数: email, password, role', StatusCode.BAD_REQUEST)

        # 连接数据库
        connection = get_db_connection()

        try:
            with connection.cursor() as cursor:
                sql = """
                SELECT user_id, email, username, role, password
                FROM user 
                WHERE email = %s AND role = %s
                """
                cursor.execute(sql, (email, role))
                user = cursor.fetchone()

                if user:
                    # 修正：验证密码（比较哈希值）
                    if verify_password(password, user['password']):
                        # 生成token
                        token = generate_token()

                        # 更新最后登录时间
                        try:
                            update_sql = "UPDATE user SET last_login_time = %s WHERE user_id = %s"
                            cursor.execute(update_sql, (datetime.now(), user['user_id']))
                            connection.commit()
                        except Exception as e:
                            print(f"更新last_login失败: {e}")
                            pass

                        # 设置token过期时间
                        expires = get_token_expires(remember_me)

                        return APIResponse.success(
                            data={
                                'token': token,
                                'expires': expires.isoformat(),
                                'userInfo': {
                                    'userId': user['user_id'],
                                    'email': user['email'],
                                    'role': user['role'],
                                    'username': user['username']
                                }
                            },
                            message='登录成功'
                        )
                    else:
                        return APIResponse.unauthorized('邮箱或密码错误')
                else:
                    return APIResponse.unauthorized('邮箱或密码错误')

        finally:
            connection.close()

    except Exception as e:
        return APIResponse.server_error(f'服务器错误: {str(e)}')
